import json

import requests

headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Pragma": "no-cache",
    "Referer": "https://www.cninfo.com.cn/new/disclosure/stock?plate=&stockCode=600887&orgId=gssh0600887",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
    "sec-ch-ua": "\"Chromium\";v=\"142\", \"Google Chrome\";v=\"142\", \"Not_A Brand\";v=\"99\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\""
}


### 利润表
def get_income_statement(scode):
    return requests.get(
        url="https://www.cninfo.com.cn/data20/financialData/getIncomeStatement", headers=headers,
        params={"scode": scode, "sign": "1"}
    ).json()


### 资产负债表
def get_balance_sheets(scode):
    return requests.get(
        url="https://www.cninfo.com.cn/data20/financialData/getBalanceSheets", headers=headers,
        params={"scode": scode, "sign": "1"}
    ).json()


### 现金流量表
def get_cash_flow_statement(scode):
    return requests.get(
        url="https://www.cninfo.com.cn/data20/financialData/getCashFlowStatement", headers=headers,
        params={"scode": scode, "sign": "1"}
    ).json()


def get_all_data(scode):
    return {
        "income_statement": get_income_statement(scode),
        "balance_sheets": get_balance_sheets(scode),
        "cash_flow_statement": get_cash_flow_statement(scode)
    }


if __name__ == '__main__':
    ### 伊利股份 [600887]：伊利股份-600887   # https://www.cninfo.com.cn/new/disclosure/stock?plate=&stockCode=600887&orgId=gssh0600887#financialStatements
    ### 三元股份 [600429]：三元股份-600429   # https://www.cninfo.com.cn/new/disclosure/stock?plate=&stockCode=600429&orgId=gssh0600429#financialStatements
    key_name = ['伊利股份', '三元股份']
    all_5_data = {}
    for index, scode in enumerate(["600887", "600429"]):
        all_raw_data = get_all_data(scode)
        ### 近5年-利润表
        income_statement_recently_5_years = all_raw_data["income_statement"]["data"]["records"][0]["year"]
        ### 近5年-资产负债表
        balance_sheets_recently_5_years = all_raw_data["balance_sheets"]["data"]["records"][0]["year"]
        ### 近5年-现金流量表
        cash_flow_statement_recently_5_years = all_raw_data["cash_flow_statement"]["data"]["records"][0]["year"]

        all_5_data[key_name[index]] = {
            "income_statement": income_statement_recently_5_years,
            "balance_sheets": balance_sheets_recently_5_years,
            "cash_flow_statement": cash_flow_statement_recently_5_years
        }
    with open('./data/financial_data.json', 'w', encoding='utf-8') as f:
        f.write(json.dumps(all_5_data, ensure_ascii=False, indent=4))
    print('financial_data=>', all_5_data)
